package touro.mancala.master;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.logging.Level;
import java.util.logging.Logger;

import touro.mancala.core.Constants;

/**
 * Listens for slaves on port 5771
 * When a slave connects it will add the slave to the slave pool
 * @author Student
 *
 */
public class SlaveAcceptListener implements Runnable {
	private static final Logger logger = Logger.getLogger(ClientAcceptListener.class.getName());

	private ServerSocket serverSocket;
	private boolean closed;
	private Server server;

	public SlaveAcceptListener(Server server) throws IOException{
		serverSocket = new ServerSocket(Constants.SLAVE_PORT);
		closed = false;
		this.server = server;

		logger.log(Level.INFO, "Listening for Slaves on " + Constants.SLAVE_PORT);
	}
	
	public void run(){
		try {			
			while (!closed) {

				logger.log(Level.INFO, "Accepting Slave Connections");
				Socket socket = serverSocket.accept();
				
				logger.log(Level.INFO, "Handling Client connection from " + socket.getInetAddress());
				server.getSlaveManager().getSlaves().add(socket);
				SlaveSocketHandler handler = new SlaveSocketHandler(server,socket);
				new Thread(handler).start();
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
}
